
package cn.bdqn.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import cn.bdqn.util.ConfigManager;

public class BaseDao {

	protected  Connection con; //链接
	protected  ResultSet rs;   //结果集
	protected  PreparedStatement ps; //参数

	// 获取数据库链接
/*	public Connection getConnection() {
	try {
		Context context=new InitialContext();
	DataSource dataSource=	(DataSource) context.lookup("java:comp/env/jdbc/news");
	con=dataSource.getConnection();
	} catch (Exception e) {
		e.printStackTrace();
	}
		return con;
	}*/
	// 获取数据库链接
	public boolean getConnection() {
		String driver = ConfigManager.getInstance().getString(
				"jdbc.driverClass");
		String url = ConfigManager.getInstance().getString(
				"jdbc.connection.url");
		String username = ConfigManager.getInstance().getString(
				"jdbc.connection.username");
		String password = ConfigManager.getInstance().getString(
				"jdbc.connection.password");
		try {
			// 加载数据库驱动
			Class.forName(driver);
			// 获取数据库链接
			con = DriverManager.getConnection(url, username, password);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	// 增删改
	public int executeUpdate(String sql, Object...params) {
		getConnection();
		int updateRows=0;
		try {
			ps = con.prepareStatement(sql);
			for (int i = 0; i <params.length; i++) {
				ps.setObject(i + 1, params[i]);
			}
			updateRows = ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return updateRows;
	}

	
	// 查询
	public ResultSet executeSQL(String sql, Object[]params) {
		getConnection();
		try {
			ps = con.prepareStatement(sql);
			for (int i = 0; i < params.length; i++) {
				ps.setObject(i + 1, params[i]);
			}
			rs = ps.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}

	// 关闭资源
	public boolean closeResource() {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
				return false;
			}
		}
		if (ps != null) {
			try {
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
				return false;
			}
		}
		if (con != null) {
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}

}
